<template>
    <div class="weibo-card" v-if="postData">
        <div class="weibo-card__header">
            <img :src="'/img'+postData.tx" alt="avatar" class="weibo-card__avatar" />
            <div class="weibo-card__info">
                <span class="weibo-card__nickname">{{ postData.nc }}</span>
                <span class="weibo-card__meta">{{ postData.time }} 来自 微博网页版</span>
                <div class="weibo-card__meta">
                    标题# {{ postData.title }}
                </div>
            </div>
        </div>

        <div class="weibo-card__content">
            {{ postData.text }}
            <div class="weibo-card__image" v-if="postData.url && postData.url.trim()">
                <img  v-for="(imgUrl, index) in postData.url.split(',')"
                      :key="index"
                      :src="'/img'+imgUrl.trim()"
                      alt="weibo-img"
                      class="imgs"
                />
            </div>
        </div>

        <div class="weibo-card__actions">
      <span class="weibo-card__action" @click="showCommentBox = true">
        <el-icon><ChatDotRound /></el-icon>{{ totalCommentCount  }}
      </span>
            <span class="weibo-card__action" @click="handleLike">
              <el-icon class="el-icon" :class="{ 'liked': isLiked }"><Pointer /></el-icon>
              {{ likeCount }}
            </span>
            <span class="weibo-card__action" @click="handleCollect">
        <el-icon :class="{ 'collected': isCollected }"><StarFilled /></el-icon>{{ collectCount }}
      </span>
            <span class="weibo-card__action">
        <el-icon><View /></el-icon>{{ postData.browse || 0 }}
      </span>
        </div>

        <!-- 评论弹窗（对帖子的评论） -->
        <div class="comment-box" v-if="showCommentBox">
      <textarea
              v-model="commentContent"
              placeholder="说点什么好呢₍˄ ₗ   ̫ ₗ ˄₎◞ ̑̑`"
              class="comment-input"
              rows="3"
      ></textarea>
            <div class="comment-actions">
                <button class="cancel-btn" @click="showCommentBox = false">取消</button>
                <button class="send-btn" @click="sendComment">发送</button>
            </div>
        </div>

        <!-- 评论列表-->
        <div class="comment-list">
            <div v-for="comment in commentList" :key="comment.commentId" class="comment-item">
                <div class="comment-header">
                    <img :src="'/img' + comment.avatar" class="qwe"/>
                    <div class="comment-info">
                        <span class="comment-nickname">{{ comment.nickname }}</span>
                        <span class="comment-time">{{ comment.commentTime }}</span>
                    </div>
                    <div class="comment-actions">
                        <el-button type="text" @click="showCommentDetail(comment, false)">详情</el-button>
                        <el-button type="text" @click="toggleReplyBox(comment)">回复</el-button>
                    </div>
                </div>
                <div class="comment-content">
                    {{ comment.commentContent }}
                </div>

                <!-- 回复输入框 -->
                <div v-if="comment.showReplyBox" class="reply-input-box" @click.stop>
                    <textarea
                            v-model="comment.replyContent"
                            :placeholder="`回复 @${comment.nickname} 点什么好呢₍˄ ₗ   ̫ ₗ ˄₎◞ ̑̑`"
                            class="reply-textarea"
                            rows="2"
                    ></textarea>
                    <div class="reply-btns">
                        <el-button size="small" @click="sendReply(comment)">发送回复</el-button>
                        <el-button size="small" type="text" @click="comment.showReplyBox = false">取消</el-button>
                    </div>
                </div>

                <!-- 子评论展示区 -->
                <div class="child-comments-container">
                    <div class="child-comments" v-if="comment.children && comment.children.length">
                        <el-divider content-position="left">回复 ({{ comment.children.length }})</el-divider>
                        <div v-for="child in comment.children" :key="child.commentId" class="child-comment-item">
                            <img :src="'/img' + child.avatar" class="child-avatar" />
                            <div class="child-comment-content">
                                <span class="child-nickname">{{ child.nickname }}</span>
                                <span class="child-reply-to"> 回复 @{{ child.repliedNickname }}</span>
                                <p class="child-text">{{ child.commentContent }}</p>
                                <div class="child-meta">
                                    <span class="child-time">{{ child.commentTime }}</span>
                                    <el-button
                                            size="mini"
                                            type="text"
                                            @click="showCommentDetail(child, true, comment)"
                                    >
                                        详情
                                    </el-button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 子评论的回复框 -->
                    <div v-if="comment.showChildReplyBox" class="reply-input-box" @click.stop>
                        <textarea
                                v-model="comment.childReplyContent"
                                :placeholder="`回复 @${comment.currentChildNickname || '用户'}...`"
                                class="reply-textarea"
                                rows="2"
                        ></textarea>
                        <div class="reply-btns">
                            <el-button size="small" @click="sendChildReply(comment)">发送回复</el-button>
                            <el-button size="small" type="text" @click="comment.showChildReplyBox = false">取消</el-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 评论详情弹窗（支持主评论和子评论） -->
        <el-dialog
                :title="isChildComment ? '回复详情' : '评论详情'"
                v-model="dialogVisible"
                width="500px"
        >
            <div v-if="currentComment">
                <p><strong>评论人：</strong>{{ currentComment.nickname }}</p>
                <p><strong>内容：</strong>{{ currentComment.commentContent }}</p>
                <p><strong>时间：</strong>{{ currentComment.commentTime }}</p>
                <p v-if="isChildComment && currentComment.repliedNickname">
                    <strong>回复对象：</strong>{{ currentComment.repliedNickname }}
                </p>
            </div>
            <template #footer>
                <el-button @click="dialogVisible = false">关闭</el-button>
                <el-button
                        type="danger"
                        @click="deleteComment(currentComment, isChildComment)"
                        :disabled="currentComment.userId !== userId"
                >
                    删除
                </el-button>
            </template>
        </el-dialog>

    </div>

    <div v-else>加载中...</div>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ref, onMounted } from 'vue';
import { ChatDotRound, StarFilled, View, Pointer } from '@element-plus/icons-vue';
import { useRoute } from 'vue-router';
import { ElDialog, ElButton, ElDivider } from 'element-plus';
import { useUserStore } from "@/stores/user";
import { onBeforeRouteUpdate } from 'vue-router'

const userStore = useUserStore();
const userId = userStore.id;
const route = useRoute();
const id = route.query.id;

// 帖子数据
const postData = ref<any>(null);
// 评论列表
const commentList = ref<any[]>([]);
// 评论弹窗控制
const showCommentBox = ref(false);
const commentContent = ref('');
// 详情弹窗相关
const dialogVisible = ref(false);
const currentComment = ref<any>({});
const isChildComment = ref(false); // 区分是主评论还是子评论
const currentParentComment = ref<any>(null); // 存储子评论所属的主评论

// 点赞和收藏状态
const isLiked = ref(false);
const isCollected = ref(false);
const likeCount = ref(0);
const collectCount = ref(0);

onBeforeRouteUpdate((to, from, next) => {
    const id = to.query.id
    if (id) {
        doList(id)
        doListp(id)
    }
    next()
})

onMounted(async () => {
    if (id) {
        await doList(id);
        await doListp(id);
        doListWithAllCount();
        await getLikeStatus();
        await getLikeCount();
        await getCollectStatus();
        await getCollectCount();
    } else {
        console.warn("路由参数id不存在，无法加载帖子数据");
    }
});

/**
 * 获取帖子详情
 */
const doList = async (id) => {
    const { data } = await axios.get(`/api/postAndUser/id/${id}/${userId}`);
    postData.value = data;
    likeCount.value = data.likeCount || 0;
    collectCount.value = data.collectCount || 0;
};

/**
 * 获取评论列表
 */
const doListp = async (id) => {
    const { data } = await axios.get(`/api/commentp/withReplies/${id}`);
    commentList.value = data.map(comment => ({
        ...comment,
        showReplyBox: false,
        replyContent: '',
        children: comment.children || [],
        showChildReplyBox: false,
        childReplyContent: '',
        currentChildId: null,
        currentChildNickname: ''
    }));

    // 核心：计算总评论数
    totalCommentCount.value = commentList.value.reduce(
        (sum, item) => sum + 1 + (item.children ? item.children.length : 0),
        0
    );
};

const tableData = ref([]);
const doListWithAllCount = async () => {
    const { data } = await axios.get('/api/postAndUser/allCount');
    tableData.value = data;
    console.log(data);
};

/**
 * 发送对帖子的评论
 */
const sendComment = async () => {
    if (!commentContent.value.trim()) {
        alert("评论内容不能为空！");
        return;
    }
    const postId = postData.value?.id;
    if (!postId) {
        alert("未找到帖子信息，无法评论！");
        return;
    }
    const comment = {
        postId: Number(postId),
        userId: Number(userId),
        text: commentContent.value,
        useredId: 0,
        url: null,
        parentId: null  // 表示是对帖子的评论，不是对评论的回复
    };
    if (comment.userId === 0) {
        alert("请先登录！");
        return;
    } else {
        await axios.post("/api/comment", comment);
        postData.value.commentCount = (postData.value.commentCount || 0) + 1;
        commentContent.value = "";
        showCommentBox.value = false;
        doListp(id);
        alert("评论发送成功！");
    }
};

/**
 * 显示评论详情（支持主评论和子评论）
 */
const showCommentDetail = (comment: any, isChild: boolean, parentComment?: any) => {
    currentComment.value = comment;
    isChildComment.value = isChild;
    currentParentComment.value = parentComment;
    dialogVisible.value = true;
};

/**
 * 删除评论（支持主评论和子评论）
 */
const deleteComment = async (comment: any, isChild: boolean) => {
    if (comment === null || comment === undefined) {
        alert('未选中评论，无法删除');
        return;
    }
    const commentId = comment.commentId;
    if (!commentId) {
        alert('未找到评论ID，无法删除');
        return;
    }
    const commentUserId = comment.userId;
    if (Number(userId) !== Number(commentUserId)) {
        alert('您不能删除别人的评论哦o(>﹏<)o');
        return;
    }

    // 确认删除
    if (!confirm('确定要删除这条评论吗？')) {
        return;
    }

    await axios.delete(`/api/comment/${commentId}`);

    // 如果是子评论，从父评论的children中移除
    if (isChild && currentParentComment.value) {
        currentParentComment.value.children = currentParentComment.value.children.filter(
            (child: any) => child.commentId !== commentId
        );
    }

    doListp(id);
    dialogVisible.value = false;
    alert('删除成功！');
};

/**
 * 处理点赞（原有功能）
 */
const handleLike = async () => {
    const postId = postData.value?.id;
    if (!postId || !userId) {
        alert("请先登录或帖子不存在");
        return;
    }
    if (isLiked.value) {
        const res = await axios.delete(`/api/like/${postId}/${userId}`);
        if (res.data > 0) {
            isLiked.value = false;
            likeCount.value--;
        }
    } else {
        const likeData = {
            postId: postId,
            userId: userId,
            time: new Date().toISOString()
                .replace('T', ' ')
                .slice(0, 19)
        };
        const res = await axios.post('/api/like', likeData);
        if (res.data > 0) {
            isLiked.value = true;
            likeCount.value++;
        }
    }
};

const getLikeStatus = async () => {
    const postId = postData.value?.id;
    if (postId && userId) {
        const { data: likeData } = await axios.get(`/api/like/${postId}/${userId}`);
        isLiked.value = !!likeData;
    }
};

const getLikeCount = async () => {
    const postId = postData.value?.id;
    if (postId) {
        const { data: count } = await axios.get(`/api/likes/${postId}`);
        likeCount.value = count;
    }
};

/**
 * 处理收藏（原有功能）
 */
const handleCollect = async () => {
    const postId = postData.value?.id;
    if (!postId || !userId) { alert("请先登录或帖子不存在"); return; }
    if (isCollected.value) {
        const { data: collectId } = await axios.get(`/api/collect/user/${userId}/post/${postId}`);
        if (!collectId) { alert("未找到收藏记录"); return; }
        const res = await axios.delete(`/api/collect/${collectId}`);
        if (res.data > 0) {
            isCollected.value = false;
            collectCount.value--;
        }
    } else {
        const collectData = {
            userId: userId,
            postId: postId,
            time: new Date().toISOString().replace('T', ' ').slice(0, 19)
        };
        const res = await axios.post('/api/collect', collectData);
        if (res.data > 0) {
            isCollected.value = true;
            collectCount.value++;
        }
    }
};

const getCollectStatus = async () => {
    const postId = postData.value?.id;
    if (postId && userId) {
        const { data: status } = await axios.get(`/api/collect/status/user/${userId}/post/${postId}`);
        isCollected.value = status;
    }
};

const getCollectCount = async () => {
    const postId = postData.value?.id;
    if (postId) {
        const { data: count } = await axios.get(`/api/collects/${postId}`);
        collectCount.value = count;
    }
};

/**
 * 回复相关功能
 */

// 切换主评论回复框显示/隐藏
const toggleReplyBox = (comment) => {
    // 关闭其他所有回复框
    commentList.value.forEach(item => {
        if (item.commentId !== comment.commentId) {
            item.showReplyBox = false;
            item.showChildReplyBox = false;
        }
    });
    comment.showReplyBox = !comment.showReplyBox;
    // 如果显示当前回复框，关闭子回复框
    if (comment.showReplyBox) {
        comment.showChildReplyBox = false;
    }
};


// 发送对主评论的回复
const sendReply = async (comment) => {
    if (!comment.replyContent.trim()) {
        alert("回复内容不能为空！");
        return;
    }
    const postId = postData.value?.id;
    if (!postId) {
        alert("未找到帖子信息，无法回复！");
        return;
    }
    const replyData = {
        postId: Number(postId),
        userId: Number(userId),
        text: comment.replyContent,
        useredId: 0,
        url: null,
        parentId: comment.commentId  // 关键：指定父评论ID，表示这是回复
    };
    if (replyData.userId === 0) {
        alert("请先登录！");
        return;
    }
    await axios.post("/api/comment", replyData);
    comment.showReplyBox = false;
    comment.replyContent = "";
    doListp(id);  // 重新加载评论列表
    alert("回复成功！");
};

// 发送对子评论的回复
const sendChildReply = async (comment) => {
    if (!comment.childReplyContent.trim()) {
        alert("回复内容不能为空！");
        return;
    }
    const postId = postData.value?.id;
    if (!postId || !comment.currentChildId) {
        alert("回复失败，请重试！");
        return;
    }
    const replyData = {
        postId: Number(postId),
        userId: Number(userId),
        text: comment.childReplyContent,
        useredId: 0,
        url: null,
        parentId: comment.currentChildId  // 回复子评论时，父ID是子评论的ID
    };
    if (replyData.userId === 0) {
        alert("请先登录！");
        return;
    }
    await axios.post("/api/comment", replyData);
    comment.showChildReplyBox = false;
    comment.childReplyContent = "";
    comment.currentChildId = null;
    comment.currentChildNickname = "";
    doListp(id);  // 重新加载评论列表
    alert("回复成功！");
};

const totalCommentCount = ref(0);

</script>

<style scoped>
.qwe{
    width: 60px;
    height: 60px;
    border-radius: 50%;
    object-fit: cover;
}
.weibo-card {
    display: flex;
    height: auto;
    flex-direction: column;
    background-color: #fff;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.weibo-card__header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}
.weibo-card__avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 8px;
}
.weibo-card__info {
    display: flex;
    flex-direction: column;
}
.weibo-card__nickname {
    font-weight: bold;
    color: #333;
}
.weibo-card__meta {
    font-size: 12px;
    color: #999;
}
.weibo-card__content {
    margin: 8px 0;
    text-align: center;
    color: #333;
    line-height: 1.6;
}
.weibo-card__image {
    margin-top: 8px;
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    justify-content: center;
}
.weibo-card__image img {
    max-width: 200px;
    border-radius: 4px;
}
.weibo-card__actions {
    display: flex;
    gap: 24px;
    color: #666;
    margin-top: 8px;
    cursor: pointer;
    justify-content: center;
}
.weibo-card__action {
    display: flex;
    align-items: center;
    gap: 4px;
    transition: color 0.2s;
}
.weibo-card__action:hover {
    color: #409eff;
}

/* 点赞和收藏样式 */
::v-deep .weibo-card__action .liked {
    color: #ff4d4f; /* 点赞红色 */
}
::v-deep .weibo-card__action .collected {
    color: #faad14; /* 收藏金色 */
}

/* 评论框样式 */
.comment-box {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #eee;
}
.comment-input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    resize: none;
    font-size: 14px;
}
.comment-input:focus {
    outline: none;
    border-color: #409eff;
}
.comment-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 8px;
}
.cancel-btn, .send-btn {
    padding: 6px 16px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s;
}
.cancel-btn {
    border: 1px solid #ddd;
    background-color: #fff;
    color: #666;
}
.cancel-btn:hover {
    border-color: #ccc;
    background-color: #f5f5f5;
}
.send-btn {
    border: none;
    background-color: #409eff;
    color: #fff;
}
.send-btn:hover {
    background-color: #66b1ff;
}
.imgs{
    width: 133px;
    height: 133px;
    margin: 0 2px;
}

/* 评论列表样式 */
.comment-list {
    margin-top: 16px;
    border-top: 1px solid #eee;
    padding-top: 16px;
}
.comment-item {
    padding: 12px;
    border-radius: 6px;
    background-color: #f9f9f9;
    margin-bottom: 12px;
}
.comment-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
}
.comment-info {
    margin-left: 12px;
    flex: 1;
}
.comment-nickname {
    font-weight: 500;
    margin-right: 8px;
}
.comment-time {
    font-size: 12px;
    color: #999;
}
.comment-content {
    margin-bottom: 12px;
    padding-left: 72px; /* 与头像对齐 */
}

/* 回复相关样式 */
.reply-input-box {
    margin: 8px 0;
    padding: 10px;
    background: #f5f7fa;
    border-radius: 4px;
}
.reply-textarea {
    width: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 8px;
    resize: none;
    margin-bottom: 10px;
}
.reply-textarea:focus {
    outline: none;
    border-color: #409eff;
}
.reply-btns {
    text-align: right;
}

.child-comments-container {
    margin-top: 12px;
    padding-left: 72px; /* 缩进显示，与主评论区分 */
}
.child-comments {
    margin-bottom: 12px;
}
.child-comment-item {
    display: flex;
    gap: 8px;
    padding: 8px 0;
    border-bottom: 1px dashed #f0f0f0;
}
.child-avatar {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    object-fit: cover;
}
.child-comment-content {
    flex: 1;
}
.child-nickname {
    font-weight: 500;
    margin-right: 4px;
}
.child-reply-to {
    color: #909399;
    font-size: 12px;
}
.child-text {
    margin: 4px 0;
    font-size: 14px;
}
.child-meta {
    display: flex;
    align-items: center;
    font-size: 12px;
    color: #909399;
    gap: 12px; /* 增加按钮之间的间距 */
}
.child-time {
    margin-right: 8px;
}

/* 禁用状态的删除按钮 */
::v-deep .el-button--danger.is-disabled {
    opacity: 0.6;
    cursor: not-allowed;
}
</style>
